package com.situ.crm.rbac.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.crm.common.util.Result;
import com.situ.crm.rbac.pojo.Role;
import com.situ.crm.rbac.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Gao
 * @since 2023-10-19
 */
@RestController
@RequestMapping("/rbac/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit) {
        IPage<Role> iPage = new Page<>(page, limit);
        roleService.page(iPage, null);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", iPage.getTotal());
        map.put("list", iPage.getRecords());
        return Result.ok(map);
    }

    @GetMapping("/selectAll")
    @RequestMapping(method = RequestMethod.DELETE)
    public Result selectAll() {
        List<Role> list = roleService.list();
        return Result.ok(list);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Long id) {
        boolean isSuccess = roleService.removeById(id);
        return isSuccess ? Result.ok("删除成功") : Result.error("删除失败");
    }

    @PostMapping("/add")
    public Result add(@RequestBody Role role) {
        boolean isSuccess = roleService.saveOrUpdate(role);
        return isSuccess ? Result.ok("添加成功") : Result.error("添加失败");
    }

    @GetMapping("/selectById")
    public Result selectById(Long id) {
        Role role = roleService.getById(id);
        return Result.ok(role);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Role role) {
        boolean isSuccess = roleService.saveOrUpdate(role);
        return isSuccess ? Result.ok("更新成功") : Result.error("更新失败");
    }
}

